<template>
  <a-popover trigger="click" placement="bottomLeft">
    <a-icon type="setting" style="font-size: 16px;cursor: pointer;margin-left:16px;" />
    <div slot="title">
      <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="onCheckAllChange">列展示/排序</a-checkbox>
      <a-button type="link" @click="handleReset">重置</a-button>
    </div>
    <template slot="content">
      <draggable v-model="columnsSetting" animation="300" @end="emitColumnChange">
        <div class="tools" v-for="(item, index) in columnsSetting" :key="index">
          <div class="tools-icon">
            <a-icon type="bars"/>
          </div>
          <a-checkbox v-model="item.checked" @change="onChange">{{ item.title }}</a-checkbox>
        </div>
      </draggable>
    </template>
  </a-popover>
</template>

<script>
import draggable from 'vuedraggable'
export default {
  props: {
    columns: {
      type: Array,
      default: () => ([])
    }
  },
  components: {
    draggable
  },
  data () {
    return {
      indeterminate: false,
      checkAll: true,
      columnsSetting: [],
      defaultColumn: []
    }
  },
  mounted () {
    this.columnsSetting = this.columns.map(value => ({ ...value, checked: true }))
    this.defaultColumn = JSON.parse(JSON.stringify(this.columnsSetting))
  },
  methods: {
    onChange () {
      const checkedList = this.columnsSetting.filter(value => value.checked)
      this.indeterminate = !!checkedList.length && checkedList.length < this.columnsSetting.length
      this.checkAll = checkedList.length === this.columnsSetting.length
      this.emitColumnChange()
    },
    onCheckAllChange (e) {
      const val = e.target.checked
      Object.assign(this, {
        indeterminate: false,
        checkAll: val,
        columnsSetting: this.columns.map(value => ({ ...value, checked: val }))
      })
      this.emitColumnChange()
    },
    handleReset () {
      this.columnsSetting = JSON.parse(JSON.stringify(this.defaultColumn))
      this.indeterminate = false
      this.checkAll = true
      this.emitColumnChange()
    },
    emitColumnChange () {
      this.$emit('columnChange', this.columnsSetting)
    }
  }
}
</script>
<style lang="less" scoped>
  .tools {
    margin-bottom: 6px;
    cursor: move;
    .tools-icon {
      display: inline-block;
      margin-right: 6px;
    }
  }
</style>
